package service

import (
	"fmt"
	"github.com/mojocn/base64Captcha"
	"ruoyi-go/internal/core/constants"
	"ruoyi-go/internal/framework/redisclient"
	"strings"
)

type Captcha struct {
	Uuid    string
	Img     string
	Code    string
	Enabled bool
}

var store = base64Captcha.DefaultMemStore // 默认内存存储，其实用不到。实际用的是redis

// GetCaptcha 生成验证码
func GetCaptcha() (Captcha, error) {
	// 创建数字验证码配置
	driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.8, 80)
	// 创建验证码
	captcha := base64Captcha.NewCaptcha(driver, store)
	// 生成验证码
	uuid, b64s, answer, err := captcha.Generate()
	// 缓存到redis
	captchaKey := fmt.Sprintf("%s%s", constants.CAPTCHA_CODE_KEY, uuid)
	if e := redisclient.SetexObj(captchaKey, &answer, constants.CAPTCHA_EXPIRATION*60); e != nil {
		return Captcha{}, e
	}
	return Captcha{
		Uuid:    uuid,
		Img:     strings.TrimPrefix(b64s, "data:image/png;base64,"),
		Code:    answer,
		Enabled: true,
	}, err
}

// ValidateCaptcha 校验验证码
func ValidateCaptcha(uuid, answer string) error {
	// 验证用户输入
	captchaKey := fmt.Sprintf("%s%s", constants.CAPTCHA_CODE_KEY, uuid)
	obj, err := redisclient.GetObj[string](captchaKey)
	if err != nil { // 验证码过期
		return fmt.Errorf("user.jcaptcha.expire")
	}
	if (*obj) != answer { // 验证码过期或者错误
		return fmt.Errorf("user.jcaptcha.error")
	}
	redisclient.DeleteObj(captchaKey) // 清理redis
	store.Get(uuid, true)             // 清理本地存储
	return nil
}
